package cn.mrcode.wxsdk.core.zkhelper.curator;

import cn.mrcode.wxsdk.core.context.ConfigContext;
import cn.mrcode.wxsdk.core.dialogue.common.accessToken.lifeCycle.distributed.strategy.master.AccessTokenDistributedTaskMaster;
import org.apache.curator.framework.CuratorFramework;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 *  查找leader的路径
 * @author zhuqiang
 * @version V1.0
 * @date 2016/6/28
 */
public class FindRuningLockPathHelper {
    private static Logger log = LoggerFactory.getLogger(FindRuningLockPathHelper.class);

    public static ArrayList<String> find(ConfigContext configContext, String masterPath){
        ConfigContext.DistributedConfig dirstributedConfig = configContext.getDirstributedConfig();
        int sessionTimeout = dirstributedConfig.getSessionTimeout();
        String zkServiceList = dirstributedConfig.getZkServiceList();
        return find(ClientHelper.createClient(zkServiceList, sessionTimeout),masterPath);
    }

    /**
     *
     * @param client 链接zk的客户端
     * @param masterPath 需要查找的父级目录:比如"/basetoken"
     * @return
     */
    public static ArrayList<String> find(CuratorFramework client, String masterPath){
        try {
            byte[] bytes = client.getData().forPath(AccessTokenDistributedTaskMaster.runingPath);
            String runingBody = new String(bytes);
            log.debug("runingBody: " + runingBody);
            return find(client,masterPath,runingBody);
        } catch (Exception e) {
            log.error("查找出错：" + e.getMessage());
            e.printStackTrace();
        }

        return null;
    }

    /**
     *
     * @param client 链接zk的客户端
     * @param masterPath 需要查找的父级目录:比如"/basetoken"
     * @param targetChildBody 需要在该目录下查找对象的内容
     * @return
     */
    public static ArrayList<String> find(CuratorFramework client, String masterPath,String targetChildBody){
        ArrayList<String> result = new ArrayList<>();
        try {
            List<String> childrens = client.getChildren().forPath(masterPath);
            StringBuffer childrenPathBuff = new StringBuffer();
            for (String childrenPath : childrens) {
                childrenPathBuff.delete(0,childrenPathBuff.length());
                childrenPathBuff.append(masterPath)
                        .append("/")
                        .append(childrenPath);
                String childBoyd = new String(client.getData().forPath(childrenPathBuff.toString()));
                log.debug("================ childrebsBody ==============");
                log.debug(childrenPathBuff.toString());
                log.debug(childBoyd);
                if(targetChildBody.equals(childBoyd)){
                    result.add(childrenPath);
                }
            }
        } catch (Exception e) {
            log.error("查找出错：" + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
}
